from core.models import *
from tagging.models import Tag
from photologue.models import Photo
from django.views.generic.list_detail import object_detail
from django.shortcuts import render_to_response
from django.views.generic.date_based import archive_index
from django.utils.encoding import smart_str
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from utils import DmsToDecimal
import re, logging

def get_objects(request):
    if len(request.GET)>0:
        object_type=request.GET.get('object_type', 'Thought')
        from_date=request.GET.get('from_date')
        to_date=request.GET.get('to_date')
        search_string=object_type+'.objects.filter(date_time__gte="%s", date_time__lte="%s")'% (from_date, to_date)
        res=eval(search_string)
        
        search_results_message='Your search returned '+str(len(res))+'results.'
        return render_to_response('list.html', {'latest':res, 'search_results_message':search_results_message})
    else:
        return render_to_response('search.html')
        
def whereabouts(request):
    from core.models import Event
    
    return render_to_response('calendar.html', {'objects':Event.objects.all()})

def authd_list(request):
    params={
      
    # This is bad! authd_list is hard-coded for joural entries! FIx it!
        'queryset':Event.tagged.with_any(Tag.objects.filter(name__icontains='journal')),
        'template_name':'list.html',
        'date_field':'date_time',
        'allow_future':True,
        'extra_context':{'tags':Event.tags_desc.usage(counts=True)},
        }
    if 'boring' not in request.GET:
        params['queryset']=params['queryset'].exclude(tags__contains='boring')

    for tag in request.GET.getlist('tag'):
        params['queryset']=params['queryset'].filter(name__icontains=tag)

    return archive_index(request, **params)

def whoabouts(request):
    if request.user.is_authenticated():
        access_lvl=request.user.authmeta.access_level
    else:
        access_lvl=0
    ids=Identity.objects.filter(access_level_required__lte=access_lvl)
    cv=ResumeEntry.objects.filter(access_level_required__lte=access_lvl)
    total_ids=Identity.objects.all().count()
    return render_to_response('whoabouts.html',{'ids':ids, 'cv':cv, 'access_lvl':access_lvl, 'total_ids':total_ids})

def authd_detail(request, slug, model ):
    params={
        'slug_field': 'slug',
        'slug':slug,
        'template_name':'object.html',
        }
    if request.user.is_authenticated():
        queryset=model.objects.filter(access_level_required__lte=request.user.authmeta.access_level)
    else:
        queryset=model.objects.filter(access_level_required=0)
    #Trailing slash hack. Should have a more general solution.
    slug.replace('/','')
    
    return object_detail(request, queryset,**params)

def xsendfile(request, path):
    
    #the user is attempting to view a full-res photo
    try:
        requestedPhoto=Photo.objects.get(slug=path)
        #check if they have sufficient credentials. Use short circuit logic so unauthenticated users don't cause an exception.
        if requestedPhoto.access_level_required==1 or (request.user.is_authenticated() and request.user.authmeta.access_level >= requestedPhoto.access_level_required):
            response = HttpResponse(mimetype='application/force-download')
            response['Content-Disposition'] = 'attachment; filename=%s' % requestedPhoto.image.path
            response['X-Sendfile'] = requestedPhoto.image.path
            return response
        else:
            if request.user.is_authenticated():
                clearance=request.user.authmeta.access_level
            else:
                clearance='not logged in'
            return render_to_response('classified.html', {'object':requestedPhoto})
    except Photo.DoesNotExist:
        requestedFile=ControlledFile.objects.get(path=path)
        response = HttpResponse(mimetype='application/force-download')
        response['Content-Disposition'] = "attachment; filename='%s'" % requestedFile.name
        response['X-Sendfile'] = requestedFile.full_path()
        return response

def map_all(request):
    models_dict={'photo':Photo,'events':Event}
    locations=[]
    if request.method=='GET':
        for model in request.GET.lists():
            if 'all' in model[1]:
                #look up the requested model. Using exec would not be secure.
                try:
                    objs=models_dict[model[0]].objects.filter(place__isnull=false)
                except:
                    logging.debug("couldn't map model %s" % model[0])
                for obj in objs:
                    try:
                        locations.append((obj, obj.place.coordinates.x, obj.place.coordinates.y))
                    except AttributeError:
                        logging.debug("object %s has no place" % obj)
            #if there is no 'all' in the request, then there should be 
            else:
                for pk in model[1]:
                    try:
                        obj=models_dict[model[0]].objects.get(pk=pk, place__isnull=False)
                        locations.append((obj, obj.place.coordinates.x, obj.place.coordinates.y))
                    except AttributeError:
                        logging.debug("object %s has no place" % obj)                      


    return render_to_response('map.html', {'points':locations, 'gmaps_key':settings.GOOGLE_MAPS_API_KEY})
        

def photos_map(request):
    locations=[]
    for pic in Photo.objects.filter(title__icontains='IWIC'):
        try:
            lat_dms = pic.EXIF['GPS GPSLatitude'].values
            long_dms = pic.EXIF['GPS GPSLongitude'].values
            latitude = DmsToDecimal(lat_dms[0].num, lat_dms[0].den,
                                  lat_dms[1].num, lat_dms[1].den,
                                  lat_dms[2].num, lat_dms[2].den)
            longitude = DmsToDecimal(long_dms[0].num, long_dms[0].den,
                                  long_dms[1].num, long_dms[1].den,
                                  long_dms[2].num, long_dms[2].den)
        
            locations.append((pic, longitude, latitude))

        except:
            pass

    return render_to_response('map.html', {'points':locations, 'gmaps_key':settings.GOOGLE_MAPS_API_KEY})

